<template>
    <div class="box">
        <!-- 头部搜索模块 -->
        <headerSearch :selectObj="selectObject" :isShowAdd="menuFlag" :goSearchFc="searchClick" :addFun="addDrawerForm"
            :buttonList="buttonList" />
        <!-- 中间表格模块 -->
        <BaseTable :data="portInventorytableData" :columns="portInventoryDataColumns" @details="selectDataList"
            :tableHeight="tableHeight" :pagination="false" :loading="loading"></BaseTable>

        <div class="page">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="queryAll.startpage" :page-sizes="[10, 15, 20, 25, 30]" :page-size="queryAll.pagesize"
                layout="total, sizes, prev, pager, next, jumper" :total="queryAll.totalNum"></el-pagination>
        </div>
        <!-- 交接清单-->
        <el-drawer :before-close="handleClose" title="交接清单" :visible.sync="drawerInner" direction="rtl" size="70%">
            <el-collapse v-model="activeNames">
                <el-collapse-item name="1">
                    <template slot="title">
                        <div>船舶信息</div>
                        <!-- <div style="margin-left: 82%;" @click.stop="linkClick"><el-link type="primary">上传附件</el-link>
                        </div> -->
                    </template>
                    <el-form :model="lottingForm" size="small" style="padding:20px 10px;" label-position="top"
                        label-width="100px">
                        <el-row :gutter="20">
                            <el-col :span="6">
                                <el-form-item label="船名航次">
                                    <el-input v-model="detailsData.shipvoyageName" :disabled="true"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="货种">
                                    <el-input v-model="detailsData.cargoCategoryName" :disabled="true"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="靠泊时间">
                                    <el-input v-model="detailsData.berthTime" :disabled="true"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <el-form-item label="离泊时间">
                                    <el-input v-model="detailsData.leaveBerthTime" :disabled="true"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </el-collapse-item>
                <el-collapse-item name="2">
                    <template slot="title">
                        <div>货物信息</div>
                        <div v-if="detailsData.listStatus == '1'" style="margin-left: 82%;" @click.stop="addLotting">
                            <el-link type="primary">复制</el-link>
                        </div>
                    </template>
                    <el-form :model="lottingForm" ref="basisRulesRef" size="small">
                        <el-table :data="lottingForm.lottingDetailedData" highlight-current-row border
                            @current-change="selectTable">
                            <el-table-column label="货主">
                                <template slot-scope="scope">
                                    <el-form-item :prop="`lottingDetailedData[${scope.$index}].cargoOwnerId`"
                                        :rules="[{ required: true, message: '货主不能为空' }]">
                                        <el-select v-model="scope.row.cargoOwnerId"
                                            @change="changeValue('cargoOwnerId', scope.$index, scope.row.cargoOwnerId)" :disabled="scope.row.bs == null? true : false">
                                            <el-option v-for="item in locationList" :key="item.customerId"
                                                :label="item.customerName" :value="item.customerId"></el-option>
                                        </el-select>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column label="货代">
                                <template slot-scope="scope">
                                    <el-form-item :prop="`lottingDetailedData[${scope.$index}].cargoAgentId`"
                                        :rules="[{ required: true, message: '货代不能为空' }]">
                                        <el-select v-model="scope.row.cargoAgentId"
                                            @change="changeValue('cargoAgentId', scope.$index, scope.row.cargoAgentId)" :disabled="scope.row.bs == null? true : false">
                                            <el-option v-for="item in locationList" :key="item.customerId"
                                                :label="item.customerName" :value="item.customerId"></el-option>
                                        </el-select>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column label="货名" prop="cargoName">
                            </el-table-column>
                            <el-table-column label="作业过程" prop="processName">
                            </el-table-column>
                            <el-table-column label="件数" width="100">
                                <template slot-scope="scope">
                                    <el-form-item :prop="`lottingDetailedData[${scope.$index}].quantity`"
                                        :rules="[{ required: true, message: '件数不能为空' }]">
                                        <el-input onkeyup="value=value.replace(/[^(\-?)\d+(\.\d+)?$]/g, '')"
                                            v-model.number="scope.row.quantity"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column label="重量" width="100">
                                <template slot-scope="scope">
                                    <el-form-item :prop="`lottingDetailedData[${scope.$index}].ton`"
                                        :rules="[{ required: true, message: '重量不能为空' }]">
                                        <el-input onkeyup="value=value.replace(/[^(\-?)\d+(\.\d+)?$]/g, '')"
                                            v-model.number="scope.row.ton"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column label="体积" width="100">
                                <template slot-scope="scope">
                                    <el-form-item :prop="`lottingDetailedData[${scope.$index}].volume`"
                                        :rules="[{ required: true, message: '体积不能为空' }]">
                                        <el-input onkeyup="value=value.replace(/[^(\-?)\d+(\.\d+)?$]/g, '')"
                                            v-model="scope.row.volume"></el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="80">
                                <template slot-scope="scope">
                                    <el-link type="danger"
                                        @click="handleDelete(scope.$index, lottingForm.lottingDetailedData)">删除</el-link>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form>
                </el-collapse-item>
            </el-collapse>
            <div class="demo-drawer__footer">
                <el-button v-if="detailsData.listStatus == '1'" type="primary" @click="submitInner()"
                    :loading="ineerLoading" size="small">
                    {{ ineerLoading ? "提交中 ..." : "保 存" }}
                </el-button>
                <el-button v-else type="warning" @click="cancelSubmit()" :loading="ineerLoading" size="small">
                    {{ ineerLoading ? "提交中 ..." : "撤 销" }}
                </el-button>
                <el-button size="small" @click="drawerInner = false">取消</el-button>
            </div>
        </el-drawer>
    </div>
</template>

<script>
import Utils from '@/libs/Utils.js'
import BaseTable from '@/components/BaseTable'
import api from '@/api/yardTally/handoverList/index'
import publicapi from '@/api/public'
import headerSearch from '@/components/headerSearch'
export default {
  components: {
    BaseTable,
    headerSearch
  },
  data() {
    return {
      menuFlag: false,
      oldOut: {},
      oldInner: {},
      ineerLoading: false,
      tableHeight: window.innerHeight - 200,
      // 搜索框显示对象
      selectObject: [
        {
          name: '船名航次',
          type: 'select',
          modelName: 'shipvoyageName',
          selectLabel: 'shipvoyageName',
          selectValue: 'shipvoyageName',
          selectData: []
        }
      ],
      // 按钮的list
      buttonList: [
        { label: '交接清单', icon: 'el-icon-tickets', type: 'primary', click: () => this.addDrawerForm, permission: 'yardDataSubsystem:Handover:insert' }
      ],
      portInventoryDataColumns: [ // table表头
        { prop: 'shipvoyageName', label: '船名航次' },
        { prop: 'cargoCategoryName', label: '货种' },
        { prop: 'loadUnload', label: '装卸' },
        { prop: 'cargoOwnerName', label: '货主', isShort: true },
        { prop: 'cargoAgentName', label: '货代', isShort: true },
        { prop: 'berthTime', label: '靠泊时间' },
        {
          prop: 'listStatus',
          label: '状态',
          render(h, params) {
            if (params.row.listStatus == '1') {
              return h('el-tag', {
                props: {
                  size: 'mini',
                  type: 'danger'
                },
                domProps: {
                  innerHTML: '未生成'
                }
              })
            }
            return h('el-tag', {
              props: {
                size: 'mini',
                type: 'success'
              },
              domProps: {
                innerHTML: '已生成'
              }
            })
          }
        }
        // { prop: 'leaveBerthTime', label: '离泊时间' },
      ],
      activeNames: ['1', '2'],
      portInventorytableData: [],
      storeHouseList: [],
      locationList: [],
      shipVoyageData: [],
      loadUnloadData: [ // 装卸
        { label: '装', value: '装' },
        { label: '卸', value: '卸' }
      ],
      loading: false,
      queryAll: {
        startpage: 1,
        pagesize: 10,
        totalNum: 0
      },
      detailsData: {},
      drawerInner: false,
      lottingForm: {
        lottingDetailedData: []
      },
      copyData: {}
    }
  },
  async activated() {
    this.getlistCustomer()
    this.getShipvoyage()
  },
  methods: {
    /**
     * 获取船名航次
     */
    async getShipvoyage() {
      const res = await publicapi.getListShipvoyage()
      this.shipVoyageData = res.data.data
      this.selectObject[0].selectData = this.shipVoyageData
    },
    // 查询货主
    async getlistCustomer() {
      await publicapi.getlistCustomer().then(res => {
        if (res.data.code == '0000') {
          this.locationList = res.data.data
        }
      })
    },
    // 获取数据
    async getData() {
      this.loading = true
      await api.getData(this.queryAll).then(res => {
        if (res.status == '200') {
          this.portInventorytableData = res.data.data.pages
          this.queryAll.startpage = res.data.data.pageNum
          this.queryAll.pagesize = res.data.data.pageSize
          this.queryAll.totalNum = res.data.data.totalNum
          this.loading = false
        }
      })
    },
    /**
         * 交接清单
         */
    async addDrawerForm() {
      if (Object.keys(this.detailsData).length == 0) {
        return this.$message.warning('请选择一条数据')
      }
      if (!this.drawerInner) {
        this.drawerInner = true
      }
      const params = {
        shipvoyageId: this.detailsData.shipvoyageId,
        listStatus: this.detailsData.listStatus
      }
      await api.getDataById(params).then(res => {
        if (res.data.code == '0000') {
          this.lottingForm.lottingDetailedData = res.data.data
        }
      })
    },
    // 选中数据
    selectDataList(val) {
      this.detailsData = {}
      this.detailsData = val
    },
    // 子表选中数据
    selectTable(val) {
      this.copyData = val
    },
    // 删除
    deleteCargoInfo(index, rows) {
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        rows.splice(index, 1);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    /**
         * 新建、编辑保存
         */
    submitInner() {
      this.$refs.basisRulesRef.validate((valid) => {
        if (valid) {
          api.updateData(this.lottingForm.lottingDetailedData).then(res => {
            if (res.data.code == '0000') {
              this.$message.success('保存成功')
              this.drawerInner = false
              this.lottingForm.lottingDetailedData = []
              this.getData()
            }
          })
        }
      })
    },
    // 撤销
    cancelSubmit() {
      api.deleteData(this.lottingForm.lottingDetailedData).then(res => {
        if (res.data.code == '0000') {
          this.$message.success('撤销成功')
          this.drawerInner = false
          this.lottingForm.lottingDetailedData = []
          this.getData()
        }
      })
    },
    searchClick(searchData) {
      this.queryAll.startpage = 1
      this.queryAll = Object.assign(this.queryAll, searchData)
      this.detailsData = {}
      this.getData()
    },
    // 添加明细信息
    addLotting() {
      if (!this.copyData.processCode) {
        return this.$message.warning('请选择一条数据')
      }
      const data = {
        shipvoyageId: this.detailsData.shipvoyageId,
        companyId: this.copyData.companyId,
        packing: this.copyData.packing,
        tradeType: this.copyData.tradeType,
        cargoInfoId: this.copyData.cargoInfoId,
        issuingCompanyId: this.copyData.issuingCompanyId,
        trustId: this.copyData.trustId,
        cargoOwnerId: this.copyData.cargoOwnerId,
        cargoOwnerName: this.copyData.cargoOwnerName,
        cargoAgentId: this.copyData.cargoAgentId,
        cargoAgentName: this.copyData.cargoAgentName,
        cargoCode: this.copyData.cargoCode,
        cargoName: this.copyData.cargoName,
        processCode: this.copyData.processCode,
        processName: this.copyData.processName,
        quantity: this.copyData.quantity,
        ton: this.copyData.ton,
        volume: this.copyData.volume,
        bs: '1'
      }
      this.lottingForm.lottingDetailedData.push(data)
    },
    async changeStorehouseId(index, row) {
      this.lottingForm.lottingDetailedData[index].locationId = ''
      this.lottingForm.lottingDetailedData[index].storehouseName = this.storeHouseList.filter(item => item.storehouseId == row)[0].storehouseName
      await publicapi.getStorehouseLocation(row).then(res => {
        if (res.data.code == '0000') {
          this.lottingForm.lottingDetailedData[index].locationList = res.data.data
        }
      })
    },
    // 下拉框数据
    changeValue(type, index, val) {
      if (type == 'cargoOwnerId') {
        this.lottingForm.lottingDetailedData[index].cargoOwnerName = this.locationList.filter(item => item.customerId == val)[0].customerName
      } else if (type == 'cargoAgentId') {
        this.lottingForm.lottingDetailedData[index].cargoAgentName = this.locationList.filter(item => item.customerId == val)[0].customerName
      }
    },
    handleDelete(index, rows) {
      if (!rows[index].bs) {
        return this.$message.warning('原始数据不能删除')
      }
      rows.splice(index, 1);
    },
    handleSizeChange(val) {
      this.queryAll.pagesize = val
      this.getData()
    },
    handleCurrentChange(val) {
      this.queryAll.startpage = val
      this.getData()
    },
    handleClose(done) {
      let oldV = {}
      let newV = {}
      if (this.drawerInner) {
        oldV = this.oldInner
        newV = this.innerForm
      }
      if (!Utils.compareData(oldV, newV)) {
        this.$confirm('修改的数据未保存，是否关闭？')
          .then(_ => {
            done()
          })
          .catch(_ => { })
      } else {
        done()
      }
    }
  }
}
</script>

<style lang="less" scoped>
@import "../../../assets/searchfrom.less";

.selectBox {
    justify-content: space-between;
    display: flex;
    background: #ffffff;
    border: 1px solid #e1e4eb;
    border-bottom: 0;
    border-left: none;
    height: 50px;
    position: relative;
    align-items: center;
    padding-left: 14px;
    padding-right: 20px;
}

.input_box {
    display: flex;
}

.page {
    background: #ffffff;
    text-align: right;
    border-radius: 0 0 4px 4px;
    padding: 5px 20px;
}

/deep/.el-drawer__body {
    margin-bottom: 30px;
}

.el-form-item--small.el-form-item {
    margin-bottom: 0px;
}
.el-table--group::after{
    background-color: rgb(45, 154, 222);
}
.el-table::before{
    height: 0;
}
/deep/ .el-drawer__header {
  margin-bottom: 0px;
  padding: 16px;
  border-bottom: 1px solid gainsboro;
}
</style>
